import {Box, Breadcrumbs, Button, Container, Grid, Link, Pagination, Paper, ThemeProvider} from "@mui/material";
import React, {useEffect} from "react";

import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import {createTheme} from "@mui/material/styles";
import {get163PlayListDetail, get163TopList} from '../../utils/request/163request'
import {getKwRank, getKwRankMusicList} from '../../utils/request/kwrequest'
import {getQRank, getQRankMusicList} from "../../utils/request/qrequest";
import Loading from "../Loading/Loading";
import Card from "./Card";
import MyTable from "../PlayList/MyTable";
import PubSub from "pubsub-js";

const theme = createTheme({
    palette: {
        primary: {
            main: 'rgba(255,255,255,0)',
            contrastText: 'black',
            light: 'rgba(255,255,255,0)'
        },
    },
});
export default function TopList(props){
    let [alignment, setAlignment] = React.useState('163');

    const handleAlignment = (event, newAlignment) => {

        if(newAlignment !== alignment && newAlignment !== null && newAlignment !== undefined) {
            //console.log('#######')
            setAlignment(newAlignment);
            alignment = newAlignment;
            setLoading(true)
            init().then(() => {
                //console.log('#######111')
                setLoading(false);
            }).catch(() => {
                //console.log('#######222')
                setLoading(false)
            });
        }
    };
    function Tabs(){
        switch (alignment){
            case '163':
                return <NeteaseCard/>;
            case 'qq':
                return <QQCard/>
            case 'kuwo':
                return <KuwoCard/>
        }
    }
    const [anchorEl, setAnchorEl] = React.useState(null);


    //排行榜内容所在页面数字
    let [page, setPage] = React.useState(1);
    //获取所有排行榜
    const [playlist, setPlaylist] = React.useState([]);
    //排行榜分页一共有多少页
    const [pageCount, setPageCount] = React.useState(0);
    //每页排行榜内容的长度
    const [perPage, setPerPage] = React.useState(14);

    //控制loading动画的显示
    const [loading, setLoading] = React.useState(false);

    //kuwo的分类列表
    const [kuwoRank, setKuwoRank] = React.useState([]);
    //kuwo音乐的分类，目前所在分类
    const [kuwoNow, setKuwoNow] = React.useState("");

    //是否在某排行榜里，为false意思为在多个排行榜的列表页面
    const [inList, setInList] = React.useState(false);
    //当前排行榜当前页的歌曲列表
    const [listDetail, setListDetail] = React.useState([]);
    //网易是全部一起返回，所以将所有存储下来  同时qq也使用
    const [allList, setAllList] = React.useState([]);
    //当前展示排行榜的id
    const [listId, setListId] = React.useState("");




    useEffect(async () => {
        PubSub.publish("changeTopBarByUrl",'3');
        setLoading(true);
        await init().catch((r) => {
            setLoading(false)
        })
        setLoading(false)

    },[])

    async function init(){
        setInList(false);
        initPaginution();
        if(alignment === '163'){
            await get163TopList((r) => {
                //console.log(r)
                setPlaylist(r);
            })

        }else if(alignment === 'kuwo'){
            //console.log("####@@@@")
            await getKwRank((r) => {
                //console.log(r)
                setKuwoRank(r)
                setKuwoNow(r[0]?.name)
                setPlaylist(r[0]?.list)
            })
            initPaginution();
        }else if(alignment === 'qq'){
            await getQRank((r) => {
                //console.log(r)
                setKuwoRank(r)
                setKuwoNow(r[0]?.name)
                setPlaylist(r[0]?.list)
            })
        }
    }
    function initPaginution(){
        setPage(1);
    }
    function changeListRec(c){
        return () => {
            //console.log(c)
            for (const r of kuwoRank) {
                if(r.name === c){
                    setPlaylist(r.list)
                }
            }
            setKuwoNow(c);
        }
    }
    const handleChange = (event, value) => {
        page = value;
        setPage(value);
        setLoading(true);
        // searchPlayList();
        if(alignment === '163' || alignment === 'qq'){
            let end = page*perPage > allList.length ? allList.length : page*perPage;
            setListDetail(allList.slice((page-1)*perPage,end))
            setLoading(false);
        }else if(alignment === 'kuwo'){
            getKwRankMusicList(listId,page,perPage,(r) => {
                //console.log(page,r.v)
                setListDetail(r.v)
            }).then(() => {
                setLoading(false)
            }).catch(() => {
                setLoading(false)
            })
        }
    };

    function changeInList(props){
        setInList(!inList);
        if(props.id){
            initList(props)
        }
    }
    function initList(props){
        initPaginution();
        setListId(props.id);
        //console.log('init',props)
        setLoading(true);
        if(alignment === '163') {
            get163PlayListDetail(props.id, (r) => {
                setAllList(r.list)
                setListDetail(r.list.slice(0, perPage))
                setPageCount(r.list.length % perPage > 0 ? Math.floor(r.list.length / perPage) + 1 : r.list.length / perPage)
            }).then(() => {
                setLoading(false)
            }).catch(() => {
                setLoading(false)
            })
        }else  if(alignment === 'kuwo'){
            getKwRankMusicList(props.id,1,perPage,(r) => {
                setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
                setListDetail(r.v)
            }).then(() => {
                setLoading(false)
            }).catch(() => {
                setLoading(false)
            })
        }else if(alignment === 'qq'){
            getQRankMusicList(props.id,1,100,(r) => {
                //console.log(r)
                setAllList(r.v)
                setListDetail(r.v.slice(0, perPage))
                setPageCount(r.count % perPage > 0 ? Math.floor(r.count / perPage) + 1 : r.count / perPage)
            }).then(() => {
                setLoading(false)
            }).catch(() => {
                setLoading(false)
            })
        }
    }
    const open = Boolean(anchorEl);
    const id = open ? 'simple-popover' : undefined;
    function NeteaseCard(){
        return(
            <>
                {inList?

                    <Grid
                        container
                        direction="row"
                        justifyContent="left"
                        alignItems="flex-center"
                    >
                        <Grid item xs={12}>
                            <ThemeProvider theme={theme}>
                                <Button sx={{marginLeft:3}} color={"primary"} aria-describedby={id} variant="contained" onClick={changeInList}>
                                    返回 >
                                </Button>
                            </ThemeProvider>
                        </Grid>
                        <Grid item xs={11} marginLeft={12}>
                            <MyTable from={'163'} rows={listDetail}/>
                            <Pagination count={pageCount} onChange={handleChange} page={page} sx={{marginTop:2}}/>
                        </Grid>
                    </Grid>

                    :
                    <Grid container direction='row' justifyContent='center' item xs={12}>
                        <Grid container direction='row' justifyContent='left' marginLeft={10} item xs={11}>
                            {playlist.map((r) => {

                                return(
                                    <Card {...r} key={r.id} f={changeInList}/>
                                )

                            })}
                        </Grid>

                    </Grid>

                }

            </>
        )
    }
    function QQCard(){
        return (
            <>
                {inList?

                    <Grid
                        container
                        direction="row"
                        justifyContent="left"
                        alignItems="flex-center"
                    >
                        <Grid item xs={12}>
                            <ThemeProvider theme={theme}>
                                <Button sx={{marginLeft:3}} color={"primary"} aria-describedby={id} variant="contained" onClick={changeInList}>
                                    返回 >
                                </Button>
                            </ThemeProvider>
                        </Grid>
                        <Grid item xs={11} marginLeft={12}>
                            <MyTable from={'qq'} rows={listDetail}/>
                            <Pagination count={pageCount} onChange={handleChange} page={page} sx={{marginTop:2}}/>
                        </Grid>
                    </Grid>

                    :
                    <>
                        <Grid container item xs={12} alignItems="center" justifyContent="center">
                            <Breadcrumbs separator="|" aria-label="breadcrumb">
                                {kuwoRank.map((r) => {
                                    return(
                                        <Link  underline="hover"
                                               color="inherit"
                                               href="#"
                                               onClick={changeListRec(r.name)}
                                               key={r.name}
                                        >

                                            <div className={`${kuwoNow === r.name? 'underline':''}`}>{r.name}</div>
                                        </Link>
                                    )
                                })}

                            </Breadcrumbs>
                        </Grid>
                        <Grid container direction='row' justifyContent='center' item xs={12}>
                            <Grid container direction='row' justifyContent='left' marginLeft={10} item xs={11}>
                                {playlist.map((r) => {

                                    return(
                                        <Card {...r} key={r.id} f={changeInList}/>
                                    )

                                })}
                            </Grid>
                        </Grid>
                    </>
                }
            </>

        )
    }
    function KuwoCard(){
        return(
            <>
                {inList?

                    <Grid
                        container
                        direction="row"
                        justifyContent="left"
                        alignItems="flex-center"
                    >
                        <Grid item xs={12}>
                            <ThemeProvider theme={theme}>
                                <Button sx={{marginLeft:3}} color={"primary"} aria-describedby={id} variant="contained" onClick={changeInList}>
                                    返回 >
                                </Button>
                            </ThemeProvider>
                        </Grid>
                        <Grid item xs={11} marginLeft={12}>
                            <MyTable from={'kuwo'} rows={listDetail}/>
                            <Pagination count={pageCount} onChange={handleChange} page={page} sx={{marginTop:2}}/>
                        </Grid>
                    </Grid>

                    :
                    <>
                        <Grid container item xs={12} alignItems="center" justifyContent="center">
                            <Breadcrumbs separator="|" aria-label="breadcrumb">
                                {kuwoRank.map((r) => {
                                    return(
                                        <Link  underline="hover"
                                               color="inherit"
                                               href="#"
                                               onClick={changeListRec(r.name)}
                                               key={r.name}
                                        >

                                            <div className={`${kuwoNow === r.name? 'underline':''}`}>{r.name}</div>
                                        </Link>
                                    )
                                })}

                            </Breadcrumbs>
                        </Grid>
                        <Grid container direction='row' justifyContent='center' item xs={12}>
                            <Grid container direction='row' justifyContent='left' marginLeft={10} item xs={11}>
                                {playlist.map((r) => {

                                    return(
                                        <Card {...r} key={r.id} f={changeInList}/>
                                    )

                                })}
                            </Grid>
                        </Grid>
                    </>
                }
            </>
        )
    }

    return(
        <Container maxWidth="xl">
            <Paper className='page' elevation={3}>
                <Loading open={loading}/>
                <Grid
                    container
                    direction="row"
                    justifyContent="center"
                    alignItems="flex-center"
                >
                    <Box sx={{ p: 3 }} />
                    <Grid container direction='row' justifyContent='right'>
                        <ToggleButtonGroup
                            value={alignment}
                            exclusive
                            onChange={handleAlignment}
                            aria-label="text alignment"
                            sx={{marginRight:10}}
                        >
                            <ToggleButton value="163" aria-label="网易云音乐">
                                <img src='./png163.png' width={32} height={32}/>
                            </ToggleButton>
                            <ToggleButton value="qq" aria-label="qq音乐">
                                <img src='./icoqq.png' width={32} height={32}/>
                            </ToggleButton>
                            <ToggleButton value="kuwo" aria-label="酷我音乐">
                                <img src='./icokuwo.png' width={32} height={32}/>
                            </ToggleButton>
                        </ToggleButtonGroup>
                    </Grid>
                    <Tabs/>
                    <Box sx={{p:6}}></Box>
                </Grid>
            </Paper>

        </Container>
    )

}